import {Component, ViewChild} from '@angular/core';

import {NavController, NavParams, InfiniteScroll} from 'ionic-angular';
import {Http} from '@angular/http';

import {parser} from '../../engine/findengine'

@Component({
  selector: 'page-section',
  templateUrl: 'section.html'
})
export class SectionPage {
  @ViewChild(InfiniteScroll) infiniteScroll: InfiniteScroll;
  selectedItem: any;
  book: { name: string, logo: string, sections: Array<any> };
  items: Array<string>;
  loadeditems:Array<string>;
  sizeOfEachPush:number = 6;
  start:number = 0;
  end:number = 0;
  showNext:boolean = false;
  currentIndex:number = 0;

  constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http,) {
    this.selectedItem = navParams.get('item');
    this.book = navParams.get('book');
    this.currentIndex = navParams.get('index');
    let url = this.selectedItem.url;
    this.items = [];
    this.loadeditems = [];
    this.showNext = false;
    this.loadImages(url);

  } // end constructor

  loadImages(url){
    this.http.get(url)
      .subscribe(data => {
        this.items = JSON.parse(parser.section_parse(data.url, data.text()));
        this.start = 0;
        this.loadeditems = [];
        if(this.start+this.sizeOfEachPush <this.items.length){
          this.end = this.start+this.sizeOfEachPush;
        }else{
          this.end = this.items.length;
        }
        for(let i = this.start; i<this.end;i++){
          this.loadeditems.push(this.items[i]);
        }
        this.start = this.end;

      }, error => {
        console.log(JSON.stringify(error.json()));
      });// end http.get
  }

  nextChapter(){
    if(this.currentIndex+1 < this.book.sections.length){
      this.showNext = false;
      this.infiniteScroll.enable(true);
      let chapter = this.book.sections[this.currentIndex+1];
      this.currentIndex += 1;
      this.selectedItem = chapter;
      this.loadImages(chapter.url);
    }
  }

  doInfinite(infiniteScroll) {
    setTimeout(() => {
      if(this.start+this.sizeOfEachPush <this.items.length){
        this.end = this.start+this.sizeOfEachPush;
      }else{
        this.end = this.items.length;
      }
      for(let i = this.start; i<this.end;i++){
        this.loadeditems.push(this.items[i]);
      }
      this.start = this.end;
      infiniteScroll.complete();
      if(this.end >= this.items.length){
        this.showNext = true;
        infiniteScroll.enable(false);
      }
    }, 500);
  }

}
